package com.stu.wgt.test.utils;


import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.sql.Date;

public class JwtUtil {
    private static final String SECRET_KEY = " +tNu/jP7v2QkKRDt4RktvxRAYcYwkElpoysPnUPJ5a8=";

    public static String createToken(String role) {
        long currentTimeMillis = System.currentTimeMillis();
        long expirationTimeMillis = currentTimeMillis + 3600000; // 1 hour

        return Jwts.builder()
                .setSubject(role) // 主题 如用户名
                .setIssuedAt(new Date(currentTimeMillis)) // 签发时间
                .setExpiration(new Date(expirationTimeMillis)) // 过期时间
                .signWith(SignatureAlgorithm.HS256, SECRET_KEY) //签名密钥
                .compact();
    }

    public static boolean verifyToken(String token) {
        try {
            Jwts.parser().setSigningKey(SECRET_KEY).parseClaimsJws(token);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    public static String getRoleFromToken(String token) {
        Claims claims = Jwts.parser().setSigningKey(SECRET_KEY).parseClaimsJws(token).getBody();
        return claims.getSubject();
    }
}
